package com.wuwei.elearning.utils.token;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 把员工工号转变成token
 */
@Component
public class TokenUtil {
    private static final String SECRET_KEY = "7B4AE8CC3FAA8E7B10B96E90AE076C6F0302657C4081ED5502EF2AF6224AF42F";
        private static final long EXPIRATION_TIME = Integer.MAX_VALUE; // 设置token的过期时间，目前是最大时间

    public static String generateToken(Long empno) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(String.valueOf(empno))
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    public static Long getAccountFromToken(String token) {
        if (token==null) {
            throw new ElearningMysqlException(40001,"token不得为空！");
        }
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();

        String subject = claims.getSubject();
        return Long.valueOf(subject);
    }

    @Resource
    private UserMapper userMapper;

    public User getUserFromToken(String token){
        Long account = TokenUtil.getAccountFromToken(token);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount,account);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null) {
            throw new ElearningMysqlException(30022,"Token不合法！无法根据account查询出用户信息！");
        } else {
            return user;
        }
    }
}
